// package_server/pages/article-detail/index.js
Page({
  data: {
    article: {},
    articleId: '',
    islike:false,
    isfavorites:false
  },
  back(){
    wx.navigateBack({
      delta: 2
    })
  },
  onLoad(options) {
    if (options.id) {
      this.setData({
        articleId: options.id
      })
      this.loadArticleDetail(options.id)
      //检查点赞状态
      this.checkLike(options.id)
      //检查收藏状态
      this.checkFavorites(options.id)
    }
  },
  // 加载文章详情
  async loadArticleDetail(id) {
    const res = await getApp().db.collection('eassy').doc(id).get()
    if (res.data) {
      this.setData({
        article: res.data
      })
      // 增加浏览量
      this.increaseViews(id)
    }
  },
  // 增加浏览量
  async increaseViews(id) {
    try {
      await getApp().db.collection('eassy').doc(id).update({
        data: {
          views: getApp().db.command.inc(1)
        }
      })
    } catch (error) {
      console.log('增加浏览量失败', error)
    }
  },
  //点赞终极
  likeArticle(){
    if(this.data.islike){
      this.likesCancel()//取消收藏
    }else{
      this.likeArticleing()//收藏
    }
  },
  // 进行点赞
  async likeArticleing() {
    //判断用户是否登录
    wx.getStorage({
      key:'userinfo',
      success:async (info)=>{
        let userId=info.data.openid
        let {_id,cover,title,likes}=this.data.article
        //添加点赞内容进点赞数据库
        let res=await getApp().db.collection('user-eassy').add({
          data:{userId,eassyId:_id,title,cover,likes}
        })
        // 更新文章点赞数
        await getApp().db.collection('eassy').doc(_id).update({
          data: {
            likes: getApp().db.command.inc(1)
          }
        });
        this.setData({
          islike:true,
          'article.likes':likes + 1
        })
        wx.showToast({
          title: '点赞成功',
          icon:'none'
        })
      },
      fail:(err)=>{
        wx.showModal({
          title: '登陆后操作',
          content: '是否跳转到个人中心授权登录',
          complete: (res) => {
            if (res.cancel) {
            }
            if (res.confirm) {
              wx.switchTab({
                url: '../../../pages/main/index',
              })
            }
          }
        })
      }
    })
  },
  //检查点赞状态
  async checkLike(articleId){
    let userId=getApp().userinfo?.openid
    let res=await getApp().db.collection('user-eassy').where({eassyId:articleId,userId}).get()
    if(res.data.length){
      this.setData({islike:true})
    }
  },
  //取消点赞
  async likesCancel(){
    let userId=getApp().userinfo?.openid
    let {_id,likes}=this.data.article
    let recode= await getApp().db.collection('user-eassy').where({userId,eassyId:_id}).get()
    console.log('取消点赞数组',recode);
    if(recode.data.length>0){
      await getApp().db.collection('user-eassy').doc(recode.data[0]._id).remove()
    }
    //更新点赞数
    await getApp().db.collection('eassy').doc(_id).update({
      data:{likes:likes - 1}
    })
    //ui上面的
    this.setData({
      islike:false,
      'article.likes':likes - 1
    })
    wx.showToast({
      title: '取消点赞',
      icon:'none'
    })
  },
  //终极收藏
  favoriteArticle(){
    if(this.data.isfavorites){
      this.favoritesCancel()//取消收藏
    }else{
      this.favoriteArticleing()//收藏
    }
  },
  // 收藏
  async favoriteArticleing() {
    //判断用户是否登录
    wx.getStorage({
      key:'userinfo',
      success:async (info)=>{
        let userId=info.data.openid
        let {_id,cover,title,favorites}=this.data.article
        //添加文章内容进收藏数据库
        let res=await getApp().db.collection('user-favorte').add({
          data:{userId,eassyId:_id,title,cover,favorites}
        })
        // 更新文章收藏数
        await getApp().db.collection('eassy').doc(_id).update({
          data: {
            likes: getApp().db.command.inc(1)
          }
        });
        this.setData({
          isfavorites:true,
          'article.favorites':favorites + 1
        })
        wx.showToast({
          title: '收藏成功',
          icon:'none'
        })
      },
      fail:(err)=>{
        wx.showModal({
          title: '登陆后操作',
          content: '是否跳转到个人中心授权登录',
          complete: (res) => {
            if (res.cancel) {
            }
            if (res.confirm) {
              wx.switchTab({
                url: '../../../pages/main/index',
              })
            }
          }
        })
      }
    })
  },
  //检查收藏状态
  async checkFavorites(articleId){
    let userId=getApp().userinfo?.openid
    let res=await getApp().db.collection('user-favorte').where({eassyId:articleId,userId}).get()
    if(res.data.length){
      this.setData({isfavorites:true})
    }
  },
  //取消收藏
  async favoritesCancel(){
    let userId=getApp().userinfo?.openid
    let {_id,favorites}=this.data.article
    let recode= await getApp().db.collection('user-favorte').where({userId,eassyId:_id}).get()
    if(recode.data.length>0){
      await getApp().db.collection('user-favorte').doc(recode.data[0]._id).remove()
    }
    //更新收藏数
    await getApp().db.collection('eassy').doc(_id).update({
      data:{favorites:favorites - 1}
    })
    //ui上面的
    this.setData({
      isfavorites:false,
      'article.favorites':favorites - 1
    })
    wx.showToast({
      title: '取消收藏',
      icon:'none'
    })
  },

  back() {
    wx.navigateBack()
  }
}) 